package com.gxa.service.impl;

import com.gxa.exception.CustomerException;
import com.gxa.service.SmsService;
import com.gxa.utils.MessageCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author lch
 * @date 2024/3/25 15:37
 * @description 发送短信
 **/
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    //用户登录短信前缀
    public final static  String USER_LOGIN_SMS="user_login_sms:";

    //短信过期时间5分钟
    public final static  Integer USER_LOGIN_EXPIRE=60*5;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送验证码
     * @param phone
     */
    @Override
    public String sendSms(String phone) {

        //判断手机号是否正确
        if(!phone.matches("^1[3-9]\\d{9}$")){
            throw new CustomerException(MessageCode.PHONE_ERROR);
        }

        //生成6位验证码
        StringBuilder str= new StringBuilder();
        for (int i=0;i<6;i++){
            str.append(new Random().nextInt(10));
        }
         String code=str.toString();

        //把验证码保存到redis中
        redisTemplate.boundValueOps(USER_LOGIN_SMS+phone).set(code);

        //设置验证码的失效时间
        redisTemplate.boundValueOps(USER_LOGIN_SMS+phone).expire(USER_LOGIN_EXPIRE, TimeUnit.SECONDS);

        log.info("手机号码:{},登录验证码：{}",phone,code);

        //返回验证码
        return code;
    }
}
